package com.yimi.yinhepda.views.sort_module;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.pda.ym.entity.response.NoDataResponse;
import com.pda.ym.utils.SysInfo;
import com.yimi.yinhepda.R;
import com.pda.ym.base.BaseActivity;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.DepartmentTableDao;
import com.yimi.yinhepda.db.dao.LineVoTableDao;
import com.yimi.yinhepda.db.dao.SortScanTableDao;
import com.yimi.yinhepda.db.dao.StorageDetailTableDao;
import com.yimi.yinhepda.db.dao.StorageInfoTableDao;
import com.yimi.yinhepda.db.table.DepartmentTable;
import com.yimi.yinhepda.db.table.LineVoTable;
import com.yimi.yinhepda.db.table.SortScanTable;
import com.yimi.yinhepda.db.table.StorageDetailTable;
import com.yimi.yinhepda.db.table.StorageInfoTable;
import com.yimi.yinhepda.downLoadBaseData.DownLoadBaseData;
import com.yimi.yinhepda.entity.request.QueryStorageInfoRequest;
import com.yimi.yinhepda.entity.response.QueryStorageInfoResponse;
import com.yimi.yinhepda.entity.response.QueryWaybillByChildNoResponse;
import com.yimi.yinhepda.entity.response.WaybillInfo;
import com.pda.ym.net.NetRequest;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.FastClick;
import com.pda.ym.utils.SharedPreferUtil;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;
import com.yimi.yinhepda.utils.ThreadPoolUtils;
import com.yimi.yinhepda.utils.ToastUtil;
import com.yimi.yinhepda.views.stockCheck_module.StockCheckUtil;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 分拣管理界面
 * 1、下载库区资料
 * 2、启动一个线程上传未上传数据
 * 3、子单下载主单信息
 */
public class SortingActivity extends BaseActivity {
    private TextView tv_unupload_count;//未上传统计
    private TextView tv_department;//分拨中心
    private TextView tv_destcode;//库区编号
    private TextView tv_destname;//库区名称
    private TextView tv_waybill_kd;//开单数
    private TextView tv_sorting_total;//分拣总票数
    private Button btn_back;
    private Button btn_refresh;

    private String str_waybill_kd = "开单件数：";
    private String str_sort_totalbill = "分拣总票数：";
    private String logindeptNo;
    private String nextdeptNo;
    private int sortbills = 0;

    private boolean isExit = false;//是否退出上传线程
    private SortScanTableDao mSortScanTableDao = new SortScanTableDao();//分拣表
    private LineVoTableDao mLineVoTableDao = new LineVoTableDao();//线路表
    private StorageInfoTableDao mStorageInfoTableDao = new StorageInfoTableDao();//库区表

    public SortingActivity() {
        super(true);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sorting);

        initView();
        initData();
        ThreadPoolUtils.execute(new UploadRunnable());
    }

    @Override
    public void finish() {
        super.finish();
        //退出上传
        isExit = true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //退出上传
        isExit = true;
    }

    /**
     * 上传数据的线程
     */
    private class UploadRunnable implements Runnable {

        @Override
        public void run() {
            while (!isExit) {
                try {
                    //是否正在上传数据
                    if (!isDoing) {
                        //上传数据
                        uploadData();
                    }
                    Thread.sleep(5000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private boolean isDoing = false;//是否在上传数据

    //上传数据
    private synchronized void uploadData() {
        if (isDoing) {
            return;
        }
        //查询未上传数据
        final List<SortScanTable> list = mSortScanTableDao.getUnload();
        if (list != null && list.size() > 0) {
            for (SortScanTable item : list) {
                item.setIsUpload(1);
            }

            //数据上传之前校验
            final SortScanTable scanTable = list.get(0);
            if (scanTable.getInputCode() == null || scanTable.getInputCode().equals("")) {
                showToast("扫描人工号为空！");
                return;
            }
            if (scanTable.getInputUser() == null || scanTable.getInputUser().equals("")) {
                showToast("分拣人姓名为空！");
                return;
            }
            if (scanTable.getInputTime() == null || scanTable.getInputTime().equals("")) {
                showToast("扫描时间为空！");
                return;
            }
            if (scanTable.getUpdateTime() == null || scanTable.getUpdateTime().equals("")) {
                showToast("上传时间为空！");
                return;
            }
            if (scanTable.getWaybillChildNo() == null || scanTable.getWaybillChildNo().equals("")) {
                showToast("子单为空！");
                return;
            }
            if (scanTable.getWaybillNo() == null || scanTable.getWaybillNo().equals("")) {
                showToast("主单为空！");
                return;
            }
            if (scanTable.getEquipmentCode() == null || scanTable.getEquipmentCode().equals("")) {
                String imei = SysInfo.getInstance().getImei();
                if (imei == null || imei.equals("")) {
                    showToast("设备编码为空！");
                    return;
                } else {
                    scanTable.setEquipmentCode(imei);
                }
            }
            if (scanTable.getEquipmentType() == null || scanTable.getEquipmentType().equals("")) {
                String phoneModle = SysInfo.getInstance().getPhoneModel();
                if (phoneModle == null || phoneModle.equals("")) {
                    showToast("设备类型为空！");
                    return;
                } else {
                    scanTable.setEquipmentType(phoneModle);
                }
            }
            if (scanTable.getDeptCode() == null || scanTable.getDeptCode().equals("")) {
                showToast("所属网点为空！");
                return;
            }

            isDoing = true;

            new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                    .setResponsClazz(NoDataResponse.class)
                    .setUrl(Constants.URL_UPLOAD_SORT)
                    .setRequestObject(scanTable)
                    .execute(new UICallBack() {
                        @Override
                        public void onError(String msg) {
                            isDoing = false;
                        }

                        @Override
                        public void onSuccess(Object obj) {
                            if (obj instanceof NoDataResponse) {
                                try {
                                    mSortScanTableDao.update(scanTable);
                                } catch (SQLException e) {
                                    e.printStackTrace();
                                }
                                //减少未上传数据
                                decreaseUnloadCount(1);
                            }
                            isDoing = false;
                        }
                    });
        } else {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    setUnloadCount("0");
                }
            });
        }
    }

    private synchronized void setUnloadCount(String count) {
        //设置未上传数
        tv_unupload_count.setText(count);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //推出时存储当前已扫总票
        SharedPreferUtil.getInstance().setSortingTotalBill(sortbills + "");
    }

    @Override
    public String getPageName() {
        return "分拣扫描";
    }

    private void initView() {
        btn_back = findViewById(R.id.sorting_scan_back);
        btn_back.setOnClickListener(this);
        btn_refresh = findViewById(R.id.sorting_scan_refresh);
        btn_refresh.setOnClickListener(this);

        tv_unupload_count = findViewById(R.id.num);
        tv_department = findViewById(R.id.tv_department);
        tv_destcode = findViewById(R.id.tv_destcode);
        tv_destname = findViewById(R.id.tv_destname);
        tv_waybill_kd = findViewById(R.id.tv_waybill_kd);
        tv_sorting_total = findViewById(R.id.tv_sorting_total);
    }

    private void initData() {

        ((TextView) findViewById(R.id.title)).setText(getPageName());

        sortbills = Integer.parseInt(SharedPreferUtil.getInstance().getSortingTotalBill());

        tv_department.setText("");
        tv_destcode.setText("");
        tv_destname.setText("");
        tv_sorting_total.setText(str_sort_totalbill + sortbills);
        tv_unupload_count.setText(mSortScanTableDao.queryCount("isUpload", 0) + "");

        tv_waybill_kd.setText(str_waybill_kd);
        logindeptNo = SharedPreferUtil.getInstance().getValue(Common.DEPT_CODE);
    }

    /**
     * 处理扫描条码
     */
    @Override
    protected void handleBarCode(String result) {
        super.handleBarCode(result);
        if (result == null) {
            SoundVibratorManager.playSound(2);
            showToast("扫描条码错误！");
        } else {
            sorting(result);
        }
    }

    private void sorting(String result) {
        //判断是否正确
        if (!StringUtils.isWaybillNo(result)) {
            showToast("运单号不规范!");
            SoundVibratorManager.playSound(2);
            return;
        }
        //子单下主单信息
        downloadWaybillNo(result);
    }

    //子单下载主单
    private void downloadWaybillNo(final String result) {
        //关闭扫描
        setScannerEnabled(false);
        showPgDlg("正在子单下载主单...");

        Map<String, String> params = new HashMap<>();
        params.put("childWaybillNo", result);

        //扫描数据上传完后  调完成任务
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(QueryWaybillByChildNoResponse.class)
                .setUrl(Constants.URL_FORCE_SCAN)
                .setParams(params)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        //开启扫描
                        setScannerEnabled(true);
                        dismissPgDlg();
                        SoundVibratorManager.playSound(2);
                        showToast("子单下载主单失败:" + msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        if (obj instanceof QueryWaybillByChildNoResponse) {
                            QueryWaybillByChildNoResponse response = (QueryWaybillByChildNoResponse) obj;
                            //路由验证
                            comfirmRoute(response.getData(), result);

                            //开启扫描
                            setScannerEnabled(true);
                            dismissPgDlg();
                        }
                    }
                });
    }

    private void comfirmRoute(final WaybillInfo mWaybillInfo, String result) {
        String route = mWaybillInfo.getRouteCode();
        if (TextUtils.isEmpty(route)) {
            SoundVibratorManager.playSound(2);
            Toast.makeText(this, "错误:" + "该运单没有路由信息，请联系管理员!", Toast.LENGTH_LONG).show();
            return;
        }

        Boolean bfindRoute = false;
        String[] routelist = route.split("-");
        for (int i = 0; i < routelist.length; i++) {
            if (routelist[i].equals(logindeptNo)) {
                bfindRoute = true;
                if (i + 1 < routelist.length) {
                    nextdeptNo = routelist[i + 1];
                } else {
                    nextdeptNo = logindeptNo;
                }
                break;
            }
        }

        //没找到线路信息
        if (!bfindRoute) {
            List<LineVoTable> lineList = mLineVoTableDao.findSourceZoneCode(logindeptNo);
            if (lineList != null && lineList.size() > 0) {
                for (int k = routelist.length - 1; k >= 0; k--) {
                    for (LineVoTable item : lineList) {
                        if (item.getDestZoneCode().equals(routelist[k])) {
                            bfindRoute = true;
                            nextdeptNo = item.getDestZoneCode();
                            break;
                        }
                    }
                    if (bfindRoute) {
                        break;
                    }
                }
            } else {
                SoundVibratorManager.playSound(2);
                Toast.makeText(this, "错误:" + "没有该站点线路信息，请刷新!", Toast.LENGTH_LONG).show();
                return;
            }
        }

        if (!bfindRoute) {
            SoundVibratorManager.playSound(2);
            Toast.makeText(this, "错误:" + "无路由信息，请联系管理员!", Toast.LENGTH_LONG).show();
            return;
        }

        boolean isExist = false;
        //判断是否已扫描  同一个主单不统计
        if (mSortScanTableDao.exist(mWaybillInfo.getWaybillNo() + "")) {
            isExist = true;
        } else {
            isExist = false;
        }

        try {
            //插入数据到数据库
            SortScanTable mSortScanTable =
                    new SortScanTable(SharedPreferUtil.getInstance().getValue(Common.USER_CODE), SharedPreferUtil.getInstance().getValue(Common.USER_NAME),
                            Constants.GetScanTime(), Constants.GetSysTime(), Constants.GetScanTime(), result, mWaybillInfo.getWaybillNo() + "",
                            SysInfo.getInstance().getPhoneModel(), SysInfo.getInstance().getImei(), logindeptNo, 0);
            if (mSortScanTableDao.insert(mSortScanTable) < 0) {
                SoundVibratorManager.playSound(2);
                Toast.makeText(this, "错误:" + "数据保存失败!", Toast.LENGTH_LONG).show();
                return;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if (!isExist) {
            sortbills++;
            tv_sorting_total.setText(str_sort_totalbill + sortbills);
        }

        QueryStorageInfoRequest request = new QueryStorageInfoRequest();
        request.setDeptCode(logindeptNo);
        request.setNextDeptCode(nextdeptNo);
        StockCheckUtil.queryStorageInfo(request, new UICallBack() {
            @Override
            public void onError(String msg) {
                SoundVibratorManager.playSound(2);
                ToastUtil.showToast(msg);
            }

            @Override
            public void onSuccess(Object obj) {
                QueryStorageInfoResponse response = (QueryStorageInfoResponse) obj;
                if(response.getData() != null){
                    QueryStorageInfoRequest storageInfo = response.getData().get(0);
                    tv_destcode.setText(storageInfo.getStorageCode());
                    tv_destname.setText(storageInfo.getStorageName());
                }
                //显示下一站分拨
                DepartmentTableDao mDepartmentTableDao = new DepartmentTableDao();
                List<DepartmentTable> departmentTables = mDepartmentTableDao.queryDataByDeptCode(nextdeptNo);
                if (departmentTables != null && departmentTables.size() > 0) {
                    tv_department.setText(departmentTables.get(0).getDeptName());
                }

                tv_waybill_kd.setText(str_waybill_kd + mWaybillInfo.getQuantity());

                addUnloadCount();

                //上传数据
                uploadData();

                SoundVibratorManager.playSound(1);
            }
        });
    }

    private synchronized void addUnloadCount() {
        tv_unupload_count.setText((Integer.parseInt(tv_unupload_count.getText().toString()) + 1) + "");
    }

    private synchronized void decreaseUnloadCount(int decreaseCount) {
        //更新未上传数
        int count = Integer.parseInt(tv_unupload_count.getText().toString()) - decreaseCount;
        if (count < 0) {
            tv_unupload_count.setText("0");
        } else {
            tv_unupload_count.setText(count + "");
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (FastClick.isFastClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.sorting_scan_back:
                //推出时存储当前已扫总票
                SharedPreferUtil.getInstance().setSortingTotalBill(sortbills + "");
                finish();
                break;
            case R.id.sorting_scan_refresh:
                //下载基础数据
                new DownLoadBaseData(this, true).downloadBaseData();
                break;
            default:
                break;
        }
    }
}
